﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxControlToolkit;
using FranceTriple.Dal;

namespace TeamFranceTriple
{
    public partial class ForumPostList : BaseUserControl
    {
        private static string BackToDiscussionLocalized = "BackToDiscussion".ToLocalizedString();
        private static string onlineLocalized = "online".ToLocalizedString();
        private static string awayLocalized = "away".ToLocalizedString();
        private static string UnknownLocalized = "Unknown".ToLocalizedString();
        private static string SaidLocalized = "Said".ToLocalizedString();

        private Int32 _forumTopicId;
        public Int32 ForumCategoryId { get; set; }
        public Int32 ForumTopicId
        {
            get { return this._forumTopicId; }
            set
            {
                this._forumTopicId = value;
                var ThisTopic = ForumTopicDal.GetEntity(value);
                if (ThisTopic == null)
                    throw new HttpException(404, "This Topic has been deleted.");

                var ThisTopicLabel =   ThisTopic.LabelForumTopic;
                ForumPostEntityDataSource.WhereParameters["ForumTopicIdParam"].DefaultValue = value.ToString();
                Panel2.GroupingText = Panel2.GroupingText + " : " + ThisTopicLabel;
                ThisMaster.Page.Title = prefixTitle + ThisTopicLabel; 
            }
        }
        public Int32 ShowPostId { get; set; }
        public String UserAddressIp { get; set; }
        private Int32 UserRightLevel { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            const Int32 CurrentPostListPageSize = 15;

            Int32 PostPageNumber;
            String urlDestination;

            if (Page.RouteData.Values["postId"] != null)
                this.ShowPostId = Int32.Parse(Page.RouteData.Values["postId"].ToString());

            if (Page.RouteData.Values["topicId"] != null)
                this.ForumTopicId = Int32.Parse(Page.RouteData.Values["topicId"].ToString());
            else if (this.ShowPostId > 0)
                this.ForumTopicId = ForumTopicDal.GetTopicIdByPostId(this.ShowPostId);

            if (ForumTopicDal.GetEntity(this.ForumTopicId) == null)
                throw new HttpException(404, "This topic don't exists.");

            this.ForumCategoryId = ForumCategoryDal.GetCategoryIdByTopicId(this.ForumTopicId);

            this.UserRightLevel = UserAccessDal.UserRightLevel(this.ForumCategoryId, ((Session["AnonymousID"] == null) ? String.Empty : Session["AnonymousID"].ToString()));
            if (this.UserRightLevel == 0)
               Response.Redirect("~/" + ThisMaster.Requester.Culture + "/connexion/?returnurl=~" + Request.RawUrl);

            // Chargement des sondages et de leur question
            List<Int32> pollIds;
            pollIds = PollDal.GetPollList(this.ForumTopicId);
            if (pollIds.Count > 0)
            {
                foreach (Int32 pollId in pollIds)
                {
                    var poll = (ShowOnePoll)LoadControl("~/Pages/Polling/ShowOnePoll.ascx");
                    poll.PollId = pollId;
                    poll.UserIpAddress = ThisMaster.Requester.IpAddress;
                    poll.EditPollButtonClick += this.EditPoll_Click;
                    PollPlaceHolder.Controls.Add(poll);
                }
                ShowPollPanel.Visible = true;
            }

            // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu
            if ((Session["AnonymousID"] == null))
            {
                UnreadHyperLink.Visible = true;
                UnreadHyperLink2.Visible = true;
            }
            else
            {
                UnreadHyperLink.Visible = false;
                UnreadHyperLink2.Visible = false;
            }

            if (this.ShowPostId > 0)
            {
                if (ForumPostDal.GetEntity(this.ShowPostId) == null)
                    throw new HttpException(404, "This post don't exists.");

                PostPageNumber = ForumPostDal.GetPostIdPageNumber(this.ForumTopicId, this.ShowPostId, CurrentPostListPageSize);

                urlDestination = "~/" + ThisMaster.Requester.Culture + "/forumpost/" + this.ForumTopicId + "/?postpagenumber=" + PostPageNumber.ToString();
                Response.Redirect(urlDestination);
            }

            ShowSmiliesLiteral.Text = ForumPostDal.GetSmilies();

            // Mettre à jour le compteur de "vu le sujet"
            // mettre à jour les posts lus par user non-anonyme
            if (!IsPostBack)
            {
                // Les utilisateurs anonymes n'ont pas accès à la fonctionnalité message non-lu
                if (Session["AnonymousID"] == null)
                {
                    if (ForumPostDal.MarkAsRead(this.ForumTopicId, new Guid(ThisMaster.Requester.Membership.ProviderUserKey.ToString())))
                        ForumTopicDal.IncrementNumberOfRead(this.ForumTopicId);
                }
            }

            ForumCategory thisCategory = ForumCategoryDal.GetEntity(this.ForumCategoryId);
            BackToTopicHyperLink.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/bycategory/" + thisCategory.Id.ToString() + "/?topicpagenumber=" + ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty);
            BackToTopicHyperLink.Text = "[" + BackToDiscussionLocalized + " : " + thisCategory.LabelForumCategory + "]";
            BackToTopicHyperLink2.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/bycategory/" + thisCategory.Id.ToString() + "/?topicpagenumber=" + ((Page.RouteData.Values["topicPageNumber"] != null) ? Page.RouteData.Values["topicPageNumber"].ToString() : String.Empty);
            BackToTopicHyperLink2.Text = "[" + BackToDiscussionLocalized + " : " + thisCategory.LabelForumCategory + "]";

            HyperLink1.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/forum";
            HyperLink2.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/forum";

            HyperLink3.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/forumsearch";
            HyperLink4.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/lastpost";
            HyperLink5.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/orphan";
            HyperLink6.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/lasttopic";
            HyperLink7.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/lastpost";
            HyperLink8.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/forumsearch";
            HyperLink9.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/lasttopic";
            HyperLink10.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/orphan";

            UnreadHyperLink.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/unread";
            UnreadHyperLink2.NavigateUrl = "~/" + ThisMaster.Requester.Culture + "/topic/unread";
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            Boolean IsTopicUnlocked = ForumTopicDal.GetEntity(this.ForumTopicId).IsUnlocked;
            Boolean IsForumModerator = (UserRightLevel == RightLevel.Moderator);

            LockTopicButton.Visible = IsForumModerator && IsTopicUnlocked;
            UnlockTopicButton.Visible = IsForumModerator && !IsTopicUnlocked;

            LockTopicButton2.Visible = IsForumModerator && IsTopicUnlocked;
            UnlockTopicButton2.Visible = IsForumModerator && !IsTopicUnlocked;

            CreateForumPostPanel.Visible = IsTopicUnlocked & UserRightLevel > RightLevel.Reader;
            CreateYouTubePanel.Visible = IsTopicUnlocked & UserRightLevel > RightLevel.Reader;
            CreateImageLinkPanel.Visible = IsTopicUnlocked & UserRightLevel > RightLevel.Reader;

            if (ThisMaster.Requester.Profile == null || !((ForumTopicDal.GetEntity(this.ForumTopicId).AuthorForumTopic.ToLower() == ThisMaster.Requester.Profile.UserName.ToLower()) && IsTopicUnlocked))
                AddPollPanel.Visible = false;
        }

        protected void AddPostButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;

            if (ForumPostEditor.Content != string.Empty)
            {
                String urlDestination = String.Empty;
                Int32 newPostId;

                if (ForumPostIdLabel.Text == "0") // création d'un message
                {
                    newPostId = ForumPostDal.CreateEntity(new FranceTriple.Dal.ForumPost()
                    {
                        PostMessage = new MessageType()
                        {
                            Label = LabelForumMessageTextBox.Text,
                            Message = ForumPostEditor.Content,
                            Author = ThisMaster.Requester.Profile.UserName,
                            AuthorAdressIp = this.UserAddressIp
                        },
                        ForumTopic = ForumTopicDal.GetEntity(this.ForumTopicId)
                    });
                }
                else // Mise à jour d'un message
                {
                    newPostId = Int32.Parse(ForumPostIdLabel.Text);
                    ForumPost ForumPostUpdated = ForumPostDal.GetEntity(newPostId);
                    ForumPostUpdated.PostMessage = new MessageType()
                    {
                        Label = LabelForumMessageTextBox.Text,
                        Message = ForumPostEditor.Content,
                        Author = ThisMaster.Requester.Profile.UserName,
                        AuthorAdressIp = this.UserAddressIp
                    };

                    ForumPostDal.UpdateEntity(ForumPostUpdated);
                }

                ForumPostIdLabel.Text = "0";
                ForumPostEditor.Content = String.Empty;
                LabelForumMessageTextBox.Text = String.Empty;

                urlDestination = "/" + ThisMaster.Requester.Culture + "/forumpost/showpost/" + newPostId.ToString();
                Response.Redirect(urlDestination);
            }
        }

        protected void EditPoll_Click(object sender, PollItemEventArgs e)
        {
            Poll editingPoll = PollDal.GetEntity(e.PollId);

            PollIdLabel.Text = e.PollId.ToString();
            QuestionTextBox.Text = editingPoll.LabelPoll;
            DescriptionTextBox.Text = editingPoll.DescriptionPoll;
            DurationTextBox.Text = editingPoll.DurationInDays.ToString();

            PollAnswer[] answers = editingPoll.PollAnswer.Take(5).ToArray();
            if (answers.Length > 0)
            {
                Answer1IdLabel.Text = answers[0].Id.ToString();
                Answer1TextBox.Text = answers[0].LabelPollAnwser;
            }
            if (answers.Length > 1)
            {
                Answer2IdLabel.Text = answers[1].Id.ToString();
                Answer2TextBox.Text = answers[1].LabelPollAnwser;
            }
            if (answers.Length > 2)
            {
                Answer3IdLabel.Text = answers[2].Id.ToString();
                Answer3TextBox.Text = answers[2].LabelPollAnwser;
            }
            if (answers.Length > 3)
            {
                Answer4IdLabel.Text = answers[3].Id.ToString();
                Answer4TextBox.Text = answers[3].LabelPollAnwser;
            }
            if (answers.Length > 4)
            {
                Answer5IdLabel.Text = answers[4].Id.ToString();
                Answer5TextBox.Text = answers[4].LabelPollAnwser;
            }

            AddPollUpdatePanel.Update();
        }
        protected void AddPollButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            Int32 id = 0;
            Poll pollToUpdate = null;

            List<PollAnswer> answers = new List<PollAnswer>();
            if (Answer1IdLabel.Text != "0" || Answer2TextBox.Text != String.Empty)
                answers.Add(new PollAnswer() { Id = Int32.Parse(Answer1IdLabel.Text), LabelPollAnwser = Answer1TextBox.Text });
            if (Answer2IdLabel.Text != "0" || Answer2TextBox.Text != String.Empty)
                answers.Add(new PollAnswer() { Id = Int32.Parse(Answer2IdLabel.Text), LabelPollAnwser = Answer2TextBox.Text });
            if (Answer3IdLabel.Text != "0" || Answer3TextBox.Text != String.Empty)
                answers.Add(new PollAnswer() { Id = Int32.Parse(Answer3IdLabel.Text), LabelPollAnwser = Answer3TextBox.Text });
            if (Answer4IdLabel.Text != "0" || Answer4TextBox.Text != String.Empty)
                answers.Add(new PollAnswer() { Id = Int32.Parse(Answer4IdLabel.Text), LabelPollAnwser = Answer4TextBox.Text });
            if (Answer5IdLabel.Text != "0" || Answer5TextBox.Text != String.Empty)
                answers.Add(new PollAnswer() { Id = Int32.Parse(Answer5IdLabel.Text), LabelPollAnwser = Answer5TextBox.Text });

            id = Int32.Parse(PollIdLabel.Text);

            pollToUpdate = new Poll()
                {
                    Id = id,
                    LabelPoll = QuestionTextBox.Text,
                    DescriptionPoll = DescriptionTextBox.Text,
                    DurationInDays = Int32.Parse(DurationTextBox.Text),
                    OrderPoll = 0,
                    ForumTopic = new ForumTopic() { Id = this.ForumTopicId }
                };

            if (id == 0)
            {
                id = PollDal.CreatePollAndAnswer(pollToUpdate, answers);

                // mise à jour de l'affichage du panel des sondages
                var poll = (ShowOnePoll)LoadControl("~/Pages/Polling/ShowOnePoll.ascx");
                poll.PollId = id;
                PollPlaceHolder.Controls.Add(poll);
            }
            else
            {
                PollDal.UpdateEntity(pollToUpdate, answers);
            }

            // remise à zéro des controles de saisie d'ajout d'un sondage
            QuestionTextBox.Text = String.Empty;
            DescriptionTextBox.Text = String.Empty;
            DurationTextBox.Text = "0";

            Answer1TextBox.Text = String.Empty;
            Answer2TextBox.Text = String.Empty;
            Answer3TextBox.Text = String.Empty;
            Answer4TextBox.Text = String.Empty;
            Answer5TextBox.Text = String.Empty;

            Response.Redirect(this.Request.Url.ToString());
        }

        protected void ListView1_OnItemDeleted(object sender, ListViewDeletedEventArgs e)
        {
            Int32 rowcount = ListView1.Items.Count - 1;
            Int32 cesure;
            String urlDestination;

            // Il faut mettre à jour explicitement les compteurs
            // NumberOfMessage, la date, l'auteur et l'id du dernier message, car la Dal n'est pas appelée par la ListView.
            ForumCategoryDal.InitializeCategoryCounter(this.ForumCategoryId);

            if (rowcount <= 0)
            {
                cesure = this.Request.Url.ToString().IndexOf("?postpagenumber=");
                if (cesure > 0)
                {
                    urlDestination = this.Request.Url.ToString().Substring(0, cesure);
                    Response.Redirect(urlDestination);
                }
            }
        }

        protected void ListView1_OnItemDataBound(object sender, ListViewItemEventArgs e)
        {
            var item = e.Item;
            
            if (item.ItemType == ListViewItemType.DataItem)
            {
                String AuthorName;
                Label CreationDateForumPostLabel;
                UserProfile profile;
                Label Message;

                Gravatar Gravatar1;
                Image Bf3RankImage;
                Label NumberOfForumPostLabel;
                Label LocationLabel;
                Label Bf3GradeLabel;

                MembershipUser AuthorMembership;
                Label MemberSinceLabel;
                Label UserStatusLabel;

                ForumSignature ForumSignature1;

                ForumPost ThisForumPost = null;
                Button btn, btn2, btn3;

                ICustomTypeDescriptor descriptor = item.DataItem as ICustomTypeDescriptor;
                if (descriptor != null)
                {
                    var prop = descriptor.GetProperties()[0];
                    ThisForumPost = (ForumPost)descriptor.GetPropertyOwner(prop);
                }

                btn = item.FindControl("QuoteMessageButton") as Button;
                btn2 = item.FindControl("EditMessageButton") as Button;
                btn3 = item.FindControl("DeleteMessageButton") as Button;

                // Tout le monde peut citer un message
                if (ThisMaster.Requester.Membership != null)
                {
                    btn.Command += new CommandEventHandler(DetailButton_Command);
                }
                else
                {
                    btn.Enabled = false;

                    var btnPrivate = item.FindControl("PrivateMessageButton") as Button;
                    if (btnPrivate != null)
                        btnPrivate.Enabled = false;

                    var btnEmail = item.FindControl("EmailMessageButton") as Button;
                    if (btnEmail != null)
                        btnEmail.Enabled = false;
                }

                // seul l'auteur du message peut l'editer
                if (ThisMaster.Requester.Membership !=null && (ThisForumPost.PostMessage.Author.ToLower() == ThisMaster.Requester.Membership.UserName.ToLower()))
                {
                    btn2.Command += new CommandEventHandler(DetailButton_Command);
                }
                else
                {
                    btn2.Enabled = false;
                }

                //un modérateur ou l'auteur peuvent supprimer le message
                if (ThisMaster.Requester.Profile != null && ((UserRightLevel == RightLevel.Moderator) || (ThisForumPost.PostMessage.Author.ToLower() == ThisMaster.Requester.Profile.UserName.ToLower())))
                {
                    btn3.Enabled = true;
                }

                AuthorName = ThisForumPost.PostMessage.Author;
                profile = UserProfile.GetUserProfile(AuthorName);
                AuthorMembership = Membership.GetUser(AuthorName, false);

                Message = (Label)item.FindControl("MessageForumPostLabel");
                if (Message != null)
                    Message.Text = ForumPostDal.AutoLink(ForumPostDal.ReplaceSmiliesTextToImage(Message.Text));

                if (profile != null)
                {

                    Gravatar1 = (Gravatar)item.FindControl("Gravatar1");
                    Gravatar1.Email = profile.UserGravatarEmail;

                    Bf3RankImage = (Image)item.FindControl("Bf3RankImage");
                    Bf3RankImage.ImageUrl = profile.Bf3RankImage;

                    NumberOfForumPostLabel = (Label)item.FindControl("NumberOfForumPostLabel");
                    NumberOfForumPostLabel.Text = profile.NumberOfForumPost.ToString();

                    LocationLabel = (Label)item.FindControl("LocationLabel");
                    LocationLabel.Text = profile.Location;

                    Bf3GradeLabel = (Label)item.FindControl("Bf3GradeLabel");
                    Bf3GradeLabel.Text = profile.Bf3Grade;
                }


                MemberSinceLabel = (Label)item.FindControl("MemberSinceLabel");
                UserStatusLabel = (Label)item.FindControl("UserStatusLabel");

                if (AuthorMembership != null)
                {
                    MemberSinceLabel.Text = AuthorMembership.CreationDate.ToShortDateString();
                    UserStatusLabel.Text = (AuthorMembership.IsOnline) ? onlineLocalized : awayLocalized;
                }
                else
                {
                    MemberSinceLabel.Text = UnknownLocalized;
                    UserStatusLabel.Text = UnknownLocalized;
                }

                CreationDateForumPostLabel = (Label)item.FindControl("CreationDateForumPostLabel");
                if (CreationDateForumPostLabel != null)
                    CreationDateForumPostLabel.Text = DateTime.Parse(CreationDateForumPostLabel.Text).ToUserTimeZone(ThisMaster.Requester.Profile.TimeZone).ToString();

                ForumSignature1 = (ForumSignature)item.FindControl("ForumSignature1");
                ForumSignature1.UpperText = profile.UpperLabelSignature;
                ForumSignature1.ImageUrl = profile.ImageUrlSignature;
                ForumSignature1.NavigateUrl = profile.NavigateUrlSignature;
                ForumSignature1.BottomText = profile.BottomLabelSignature;
            }


        }

        protected void LockTopicButton_Click(object sender, EventArgs e)
        {
            ForumTopicDal.LockEntity(this.ForumTopicId);
        }

        protected void UnlockTopicButton_Click(object sender, EventArgs e)
        {
            ForumTopicDal.UnlockEntity(this.ForumTopicId);
        }

        protected void DetailButton_Command(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "EditCommand")
            {
                var ForumPostEditing = ForumPostDal.GetEntity(Int32.Parse(e.CommandArgument.ToString()));
                ForumPostIdLabel.Text = ForumPostEditing.Id.ToString();
                LabelForumMessageTextBox.Text = ForumPostEditing.PostMessage.Label;
                ForumPostEditor.Content = ForumPostEditing.PostMessage.Message;
                this.Page.SetFocus(AddPostButton.ClientID);
            }

            if (e.CommandName == "QuoteCommand")
            {
                var ForumPostEditing = ForumPostDal.GetEntity(Int32.Parse(e.CommandArgument.ToString()));
                ForumPostEditor.Content = ForumPostEditor.Content + "<fieldset style=\"display: block;text-align: left;\"><legend>" +
                    ForumPostEditing.PostMessage.Author +
                    " " + (SaidLocalized) + " : </legend><p>" +
                    ForumPostEditing.PostMessage.Message +
                    "</p></fieldset><br />";
            }
        }

        protected void AddImageLinkButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            StringBuilder sb = new StringBuilder();
            if (NavigateUrlTextBox.Text != String.Empty)
                sb.Append(String.Format("<a href=\"{0}\">", NavigateUrlTextBox.Text));

            sb.Append(String.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" title=\"{1}\"  target=\"_blank\" />", ImageUrlTextBox.Text, AlternateTextTextBox.Text));

            if (NavigateUrlTextBox.Text != String.Empty)
                sb.Append("</a>");

            //Int32 width=0;
            //Int32 height=0;
            //sb.Append(String.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" title=\"{1}\" width=\"{2}\" />", ImageUrlTextBox.Text, AlternateTextTextBox.Text, width.ToString()));
            //sb.Append(String.Format("<img src=\"{0}\" alt=\"{1}\" border=\"0\" title=\"{1}\" height=\"{2}\" />", ImageUrlTextBox.Text, AlternateTextTextBox.Text, height.ToString()));

            ForumPostEditor.Content = ForumPostEditor.Content + sb.ToString();

            NavigateUrlTextBox.Text = String.Empty;
            ImageUrlTextBox.Text = String.Empty;
            AlternateTextTextBox.Text = String.Empty;
            //WidthTextBox.Text = String.Empty;
            //HeightTextBox.Text = String.Empty;
        }

        protected void AddYouTubeButton_Click(object sender, EventArgs e)
        {
            if (!this.Page.IsValid)
                return;
            StringBuilder sb = new StringBuilder();
            if (TitleTextBox.Text != String.Empty)
                sb.Append(String.Format("<div class=\"colMain\"><fieldset class=\"Youtube\"><legend>{0}</legend><p class=\"centerP\">", TitleTextBox.Text));

            sb.Append(String.Format("<iframe width=\"580\" height=\"320\" src=\"{0}\" frameborder=\"0\" allowfullscreen></iframe></p></fieldset></div>", YouTubeUrlTextBox.Text));

            ForumPostEditor.Content = ForumPostEditor.Content + sb.ToString();

            YouTubeUrlTextBox.Text = String.Empty;
            TitleTextBox.Text = String.Empty;
        }
    }
}
